import { useMessage } from '@hooks/useAppMessage'
import { useAxios } from '@hooks/useAxios'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { API_VIDEO_URL } from './baseApi'

export const useVideoQuery = ({ title, page, per_page, sort }) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['video.list', { title, page, per_page, sort }],
    queryFn: async () => {
      return await http.get(API_VIDEO_URL, {
        params: {
          ...(title && { title }),
          sort,
          page,
          per_page,
        },
      })
    },
  })
}

export const useVideoDetailQuery = (id) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['video.detail', id],
    queryFn: async () => {
      const response = await http.get(`${API_VIDEO_URL}/${id}`)
      return response.data
    },
    enabled: !!id,
  })
}

export const useVideoUpdateMutation = () => {
  const { http } = useAxios()
  const queryClient = useQueryClient()
  const message = useMessage()
  return useMutation({
    mutationFn: async (data) => await http.put(`${API_VIDEO_URL}/${data.id}`, data),
    onSuccess: (data) => {
      queryClient.invalidateQueries(['video.list'])
      message.success('更新成功')
    },
  })
}

export const useVideoDeleteMutation = () => {
  const { http } = useAxios()
  const message = useMessage()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (ids) => await http.delete(`${API_VIDEO_URL}`, { data: { ids } }),
    onSuccess: () => {
      queryClient.invalidateQueries(['video.list'])
      message.success('删除成功')
    },
  })
}

export const useVideoCreateMutation = () => {
  const { http } = useAxios()
  const link = useNavigate()
  const message = useMessage()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (data) => await http.post(API_VIDEO_URL, data),
    onSuccess: () => {
      queryClient.invalidateQueries(['video.list'])
      message.success('保存成功')
    },
  })
}
